<script setup>
import { ref,reactive,onMounted,toRaw } from 'vue'
import {userAPI} from "../../../api/user/index.js";

const listItems = ref([])
const modalVisible = ref(false)
const visible = ref(false)
const currentRow = ref(null)
const formRef = ref()
const tableData = reactive({
  list:[]
})

const formState = reactive({
  username: '',
  nickName: '',
  phone: '',
  status: '',
  password: '',
  userId: ''
})

// 列配置增加操作列
const columns = [
  {
    title: '账号',
    dataIndex: 'username',
    key: 'username'
  },  {
    title: '姓名',
    dataIndex: 'nickName',
    key: 'nickName'
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    key: 'phone'
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status'
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    slotName:'optional'
  }
]

// 获取列表数据
const getListItems = async () => {
  const {data} = await userAPI.getList()
  console.log('res',data)
  tableData.list = data
}

onMounted(()=>{
   getListItems()
})

//提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    const api = currentRow.value
      ? userAPI.update
      : userAPI.add
    console.log('formState', toRaw(formState))
     await api(toRaw(formState))
    modalVisible.value = false
    getListItems()
    formRef.value.resetFields()
    formState.userId = ''
    formState.username = ''
    formState.nickName = ''
    formState.phone = ''
    formState.password = ''
    formState.status = ''
    currentRow.value = null
  }
  catch (error) {
    console.error('操作失败:', error)
  }
}

//显示弹窗
const showModal = (record) => {
  currentRow.value = record
  if (record) {
    Object.keys(formState).forEach(key => {
      //注意这里，数据库的字段和表单的字段不一致，需要手动映射
      if(key ==='userId'){
        formState['userId'] = record['id']
      } else {
        formState[key] = record[key]
      }
    })
  } else {
    formRef.value?.resetFields()
  }
  modalVisible.value = true
}

// 点击删除按钮
const handleClick = () => {
  visible.value = true
}

// 确认删除
const handleDelete = async (userId) => {
  try {
    console.log('userId',userId)
    await userAPI.delete(userId)
    visible.value = false
    getListItems()
  } catch (error) {
    console.error('删除失败:', error)
  }
}

// 取消删除
const handleCancel = () => {
  visible.value = false
}
</script>

<template>
<div>
  <a-button type="primary" @click="showModal()">新增用户</a-button>

  <a-table :columns="columns" :data="tableData.list">
    <template #optional="{ record }">
      <div style="display: flex;">
        <a-button type="primary" @click="showModal(record)">编辑</a-button>
        <a-button type="primary" @click="handleClick">删除</a-button>
      </div>

          <a-modal :visible="visible" @ok="handleDelete(record.id)" @cancel="handleCancel">
            <template #title>
              删除用户
            </template>
            <div>确定删除该用户吗</div>
          </a-modal>
    </template>
  </a-table>

  <a-modal
      v-model:visible="modalVisible"
      :title="currentRow ? '编辑用户' : '新增用户'"
      @ok="handleSubmit"
  >
    <a-form ref="formRef" :label-col="{ span: 6 }" :model="formState">
      <a-form-item :rules="[{ required: true, message: '请输入用户ID' }]" label="用户ID"
                   name="userId">
        <a-input v-model="formState.userId"/>
      </a-form-item>
      <a-form-item :rules="[{ required: true, message: '请输入用户名' }]" label="用户名"
                   name="username">
        <a-input v-model="formState.username"/>
      </a-form-item>
      <a-form-item :rules="[{ required: true, message: '请输入用户密码' }]" label="用户密码"
                   name="password">
        <a-input v-model="formState.password"/>
      </a-form-item>
      <a-form-item :rules="[{ required: false, message: '请输入用户昵称' }]" label="用户昵称"
                   name="nickName">
        <a-input v-model="formState.nickName"/>
      </a-form-item>
      <a-form-item :rules="[{ required: false, message: '请输入用户手机号' }]" label="用户手机号"
                   name="phone">
        <a-input v-model="formState.phone"/>
      </a-form-item>
      <a-form-item label="用户状态" name="status">
        <a-select v-model="formState.status">
          <a-option value="ACTIVE">ACTIVE</a-option>
          <a-option value="LOCKED">LOCKED</a-option>
        </a-select>
      </a-form-item>

     </a-form>
  </a-modal>
</div>
</template>

<style scoped>

</style>